package org.thanos.demo.core.dao;

import org.thanos.demo.api.enums.DeleteState;
import org.thanos.demo.core.entity.ConfigProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("configPropertiesDao")
public class ConfigPropertiesDaoImpl implements ConfigPropertiesDao {

    private static final String INSERT_SQL = "INSERT INTO config_properties (conf_key,conf_value,application,profile,label,states,version) VALUES (?,?,?,?,?,?,?)";
    private static final String DELETE_SQL = "UPDATE config_properties SET states=? WHERE id=?";
    private static final String FIND_ALL_SQL = "SELECT application, profile, label FROM config_properties WHERE states=? GROUP BY application, profile, label";
    private static final String FIND_ONE_PROFILE_SQL = "SELECT id,conf_key,conf_value,version FROM config_properties WHERE application=? AND profile=? AND label=? AND states=?";

    private static final RowMapper<ConfigProperties> rowMapper = new BeanPropertyRowMapper<>(ConfigProperties.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int insert(ConfigProperties configProperties) {
        String confKey = configProperties.getConfKey();
        String confValue = configProperties.getConfValue();
        String application = configProperties.getApplication();
        String profile = configProperties.getProfile();
        String label = configProperties.getLabel();
        Integer states = configProperties.getStates();
        String version = configProperties.getVersion();
        return jdbcTemplate.update(INSERT_SQL, confKey, confValue, application, profile, label, states, version);
    }

    @Override
    public int updateById(ConfigProperties configProperties) {
        return 0;
    }

    @Override
    public List<ConfigProperties> queryAll() {
        return jdbcTemplate.query(FIND_ALL_SQL, rowMapper, DeleteState.EFFECTIVE.getId());
    }

    @Override
    public List<ConfigProperties> queryOneProfile(String application, String profile, String label) {
        return jdbcTemplate.query(FIND_ONE_PROFILE_SQL, rowMapper, application, profile, label, DeleteState.EFFECTIVE.getId());
    }

    @Override
    public int delete(Long id) {
        return jdbcTemplate.update(DELETE_SQL, DeleteState.INVALID.getId(), id);
    }
}
